package eu.connect.im;

import com.echomine.jabber.DefaultMessageParser;
import com.echomine.jabber.JDOMXMessageHandler;
import com.echomine.jabber.JabberMessage;
import com.echomine.jabber.JabberMessageHandler;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class XMPPContentHandler extends DefaultHandler
{
	private String role;
	private JabberMessageHandler msgHandler;
	private MessageQueue queue;
	private boolean delegated;
	private String msgLocalName;
	
	public XMPPContentHandler(String role, MessageQueue queue)
	{
		this.role = role;
		this.queue = queue;
		this.msgHandler = new JDOMXMessageHandler(new DefaultMessageParser());
	}
	
	public void startDocument()
	{
		this.delegated = false;
		this.msgLocalName = null;
	}
	
	public void endDocument()
	{
	}
	
	public void startElement(String namespaceURI, String localName, String qName, Attributes attr)
	{
		if (localName.equals("stream"))
	    {
			XMPPMsgSessionInit initMsg = new XMPPMsgSessionInit(namespaceURI, localName, qName, attr);
			Message msg = new Message(initMsg, "JabberMessage", role);
			this.queue.addMessage(msg);
			return;
	    }
		
	    if (!this.delegated)
	    {
	      this.delegated = true;
	      this.msgLocalName = localName;			
	      this.msgHandler.startMessage();
	    }

	    if (this.delegated)
	      this.msgHandler.startElement(namespaceURI, localName, qName, attr);
	}
	
	public void endElement(String namespaceURI, String localName, String qName)
	{		
		if (localName.equals("stream"))
	    {
	      return;
	    }
	    
		if (this.delegated)
		{
			this.msgHandler.endElement(namespaceURI, localName, qName);
	    }
		if (localName.equals(this.msgLocalName))
		{
			this.msgHandler.endMessage();
			JabberMessage msg = this.msgHandler.getMessage();
			Message message = new Message(msg, "JabberMessage", role);
			this.queue.addMessage(message);

			this.delegated = false;
			this.msgLocalName = null;
		}
	}
	
	public void characters(char[] ch, int start, int length)
	{
		if (this.delegated)
			this.msgHandler.characters(ch, start, length);
	}
	
}
